package com.edu.controller;

import cn.hutool.core.util.StrUtil;
import com.edu.pojo.RestResult;
import com.edu.pojo.StateEnum;
import com.edu.pojo.User;
import com.edu.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author five-five
 * @created 2021/11/12 - 9:09
 */
@Api(tags = "用户相关接口", value = "用户相关接口")
@RestController
@CrossOrigin
public class UserController {
    @Resource
    private UserService userService;

    @ApiOperation("根据用户名和密码添加用户")
    @RequestMapping(value = "addUserByUserNameAndPwd", method = RequestMethod.POST)
    public RestResult addUserByUserNameAndPwd(
            @ApiParam("user")
            @RequestBody User user) {
        //判断是否有name和pwd
        if (user == null || StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getUserpwd())) {
            return RestResult.build(StateEnum.ERROR.getCode(), "用户名或密码为空，请重新输入");
        }
        return userService.addUserByUserNameAndPwd(user);
    }

    @ApiOperation("根据用户名和密码查询用户")
    @RequestMapping(value = "getUserByUserNameAndPwd", method = RequestMethod.POST)
    public RestResult getUserByUserNameAndPwd(
            @ApiParam("user")
            @RequestBody User user, HttpServletRequest request) {
        //判断是否有name和pwd
        if (user == null || StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getUserpwd())) {
            return RestResult.build(StateEnum.ERROR.getCode(), "用户名或密码为空，请重新输入");
        }
        RestResult restResult = userService.getUserByUserNameAndPwd(user);
        //把他保存至session
        HttpSession session1 = request.getSession();
        session1.setAttribute("user", restResult.getData());
        return restResult;
    }

    @ApiOperation("根据用户名和密码修改对应用户密码")
    @RequestMapping(value = "editUserPwd", method = RequestMethod.POST)
    public RestResult editUserPwd(
            @ApiParam("user")
            @RequestBody User user) {
        //判断是否有name和pwd
        if (user == null || StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getUserpwd())) {
            return RestResult.build(StateEnum.ERROR.getCode(), "用户名或密码为空，请重新输入");
        }
        return userService.editUserPwd(user);
    }
}
